﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Q7.BevTree
{
    public class BevNodeSequenceSync : BevNode
    {
        private int _currentNodeIndex = -1;

        public BevNodeSequenceSync(string debugName)
            : base(debugName)
        {
        }

        protected override bool DoEvaluate(BevNodeInputParam input)
        {
            var len = Children.Count;
            for (var i = 0; i < len; ++i)
            {
                if (!Children[i].Evaluate(input))
                {
                    return false;
                }
            }

            return true;
        }

        protected override int DoTick(BevNodeInputParam input, BevNodeOutputParam output)
        {
            var isFinish = BRS_FINISH;

            if (_currentNodeIndex == -1)
                _currentNodeIndex = 0;

            while (true)
            {
                isFinish = Children[_currentNodeIndex].Tick(input, output);

                if (isFinish != BRS_FINISH)
                    break;

                if (++_currentNodeIndex == Children.Count)
                {
                    _currentNodeIndex = -1;
                    break;
                }
            }

            if (isFinish < 0) // error

                _currentNodeIndex = -1;
            return isFinish;
        }

        protected override void DoTransition(BevNodeInputParam input)
        {
            if (CheckIndex(_currentNodeIndex))
                Children[_currentNodeIndex].Transition(input);
            _currentNodeIndex = -1;
        }
    }
}
